let chatInput = require('../../modules/chat-input/chat-input');
var utils = require("../../utils/util.js");
var websocket = require("../../utils/websocket.js");
var request = require("../../utils/request.js");
var SocketTask = null;
let socketOpen = false;
var messageList = [];
var filePath = "";
var oldIndex = null
Page({
  data: {
    wxchatLists: [],
    friendHeadUrl: '',
    chatItems: [],
    scrollTopTimeStamp: 0,
    height: 0, //屏幕高度
    chatHeight: 0, //聊天屏幕高度
    normalDataTime: '',
    toUser: {
      loginName: '',
      userName: ''
    },
    fromUser: {},
    baseUrl: null,
    scrollTop: 0,
    aduioContext: null,
    reImgUrl: null,
    index: 0,
    playId: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this;
    //创建媒体实例
    let aduioContext = wx.createInnerAudioContext()
    that.data.toUser.loginName = options.loginName;
    that.data.toUser.userName = options.userName;
    var fromUser = wx.getStorageSync('userInfo');
    var baseUrl = wx.getStorageSync('baseUrl');
    that.setData({
      fromUser: fromUser,
      baseUrl: baseUrl,
      aduioContext: aduioContext
    })
    var temp = {
      fromUserLoginName: fromUser.loginName,
      toUserLoginName: options.loginName
    }
    request.post("/message/selectMessageList", temp, function (res) {
      messageList = res.data
      that.setData({
        wxchatLists: res.data,
        scrollTop: res.data.length * 1000,
      })
    })
    that.initData();
    //获取屏幕的高度
    wx.getSystemInfo({
      success(res) {
        that.setData({
          height: wx.getSystemInfoSync().windowHeight,
          chatHeight: wx.getSystemInfoSync().windowHeight - 90
        })
      }
    });
    that.connectWebSocket(that.data.fromUser.loginName); //连接websocket
  },
  //连接服务器websocket
  connectWebSocket: function (userName) {
    var that = this
    SocketTask = websocket.connect(userName)
    socketOpen = true;
    that.onMessage()
  },
  //隐藏加载框
  onReady() {
    wx.hideLoading()
  },
  initData: function () {
    let that = this;
    let systemInfo = wx.getSystemInfoSync();
    chatInput.init(this, {
      systemInfo: systemInfo,
      minVoiceTime: 1,
      maxVoiceTime: 60,
      startTimeDown: 56,
      // 录音通道数
      numberOfChannels: 1,
      format: 'mp3', //aac/mp3
      sendButtonBgColor: 'mediumseagreen',
      sendButtonTextColor: 'white',
      extraArr: [{
        picName: 'choose_picture',
        description: '照片'
      }, {
        picName: 'take_photos',
        description: '拍摄'
      }],

    });

    that.setData({
      pageHeight: systemInfo.windowHeight,
      normalDataTime: utils.formatTime(new Date()),
    });
    wx.setNavigationBarTitle({
      title: '与' + that.data.toUser.userName + '聊天中'
    });
    that.textButton();
    that.extraButton();
    that.voiceButton();
  },
  //文本按钮
  textButton: function () {
    var that = this;
    chatInput.setTextMessageListener(function (e) {
      let content = e.detail.value;
      var temp = {
        fromAvatar: that.data.fromUser.avatar,
        fromUserName: that.data.fromUser.userName,
        toUserLoginName: that.data.toUser.loginName,
        toUserName: that.data.toUser.userName,
        content: content,
        createTime: utils.formatTime(new Date()),
        // 消息类型 0:文本；1:图片；2:语音；3:视频；4:红包
        msgType: 0,
        //判断左右两边 0右边 1左边
        type: 0
      };
      that.sendMsg(temp);
      messageList.push(temp)
      that.setData({
        wxchatLists: messageList,
        scrollTop: messageList.length * 1000,
      })
    });
  },
  //发送消息
  sendMsg: function (temp) {
    SocketTask.send({
      data: JSON.stringify(temp),
      success: (res) => {
        console.log('消息已发送')
      }
    })
  },
  //接收消息
  onMessage: function () {
    var that = this
    var list = that.data.wxchatLists;
    SocketTask.onMessage(res => {
      console.log(res.data)
      if (res.data === "连接成功") {
        console.log(res.data)
      } else {
        res = JSON.parse(res.data)
        res.type = 1
        list.push(res);
        messageList.push(res)
        that.setData({
          wxchatLists: messageList,
          scrollTop: messageList.length * 1000
        })
      }
    })
  },
  //监听左上角返回键（关闭websocket）
  onUnload: function () {
    console.log(socketOpen)
    if (socketOpen)
      SocketTask.close()
  },
  //录音按钮
  voiceButton: function () {
    var fromUser = wx.getStorageSync('userInfo');
    var that = this;
    chatInput.recordVoiceListener(function (res, duration) {
      //语音路径
      let tempFilePath = res.tempFilePath;
      //语音时长
      let vDuration = duration;
      // 上传给服务器
      request.upload('/public/uploadFile', tempFilePath, function (res) {
        if (res.code === 200) {
          console.log("上传成功的文件路径：" + res.data)
          filePath = res.data
          var temp = {
            fromAvatar: fromUser.avatar,
            fromUserName: fromUser.userName,
            toUserLoginName: that.data.toUser.loginName,
            toUserName: that.data.toUser.userName,
            content: filePath,
            voiceTime: vDuration,
            createTime: utils.formatTime(new Date()),
            // 消息类型 0:文本；1:图片；2:语音；3:视频；4:红包
            msgType: 2,
            //判断左右两边 0右边 1左边
            type: 0
          }
          that.sendMsg(temp);
          messageList.push(temp);
          that.setData({
            wxchatLists: messageList,
            scrollTop: messageList.length * 1000
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '网络请求失败，请确保网络是否正常',
            showCancel: false
          })
        }
      })
    });
    chatInput.setVoiceRecordStatusListener(function (status) {
      switch (status) {
        case chatInput.VRStatus.START: //开始录音
          break;
        case chatInput.VRStatus.SUCCESS: //录音成功
          break;
        case chatInput.VRStatus.CANCEL: //取消录音
          break;
        case chatInput.VRStatus.SHORT: //录音时长太短
          break;
        case chatInput.VRStatus.UNAUTH: //未授权录音功能
          break;
        case chatInput.VRStatus.FAIL: //录音失败(已经授权了)
          break;
      }
    })
  },
  //图片按钮
  extraButton: function () {
    let that = this;
    var baseUrl = that.data.baseUrl
    chatInput.clickExtraListener(function (e) {
      console.log(e);
      let itemIndex = parseInt(e.currentTarget.dataset.index);
      if (itemIndex === 2) {
        that.myFun();
        return;
      }
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'],
        sourceType: itemIndex === 0 ? ['album'] : ['camera'],
        success: function (res) {
          let tempFilePath = res.tempFilePaths[0];
          request.upload('/public/uploadFile', tempFilePath, function (res) {
            if (res.code === 200) {
              var temp = {
                fromAvatar: that.data.fromUser.avatar,
                fromUserName: that.data.fromUser.userName,
                toUserLoginName: that.data.toUser.loginName,
                toUserName: that.data.toUser.userName,
                dataTime: utils.formatTime(new Date()),
                content: baseUrl + res.data,
                msg_type: 1,
                type: 0
              };
              that.sendMsg(temp);
              messageList.push(temp);
              that.setData({
                wxchatLists: messageList,
                scrollTop: messageList.length * 1000
              })
            }
          })
        }
      });

    });
    // chatInput.setExtraButtonClickListener(function (dismiss) {
    //   console.log('Extra弹窗是否消息', dismiss);
    // })
  },
  resetInputStatus: function () {
    chatInput.closeExtraView();
  },
  //播放录音
  playRecord: function (e) {
    let that = this
    console.log("进入")
    var reImaUrl = "../../static/images/chat/"
    var timeId = null
    var direction = null
    var currentTime = e.currentTarget.dataset.time
    let aduioContext = that.data.aduioContext
    let type = e.currentTarget.dataset.type
    let index = e.currentTarget.dataset.index
    var voiceSrc = that.data.baseUrl + e.currentTarget.dataset.src
    //点击其他的语音出现语音重叠
    if (oldIndex != null && oldIndex != index) {
      console.log("点击其他的语音出现语音重叠")
      aduioContext.stop()
      aduioContext = wx.createInnerAudioContext()
      //点击自己的语音多次点击
    } else if (oldIndex != null && oldIndex === index) {
      console.log("点击自己的语音多次点击")
      aduioContext.stop()
      aduioContext = wx.createInnerAudioContext()
    }
    oldIndex = index
    aduioContext.src = voiceSrc
    aduioContext.play();
    //切换显示状态
    aduioContext.onPlay(function (e) {
      console.log("录音开始播放")
      if (type === 0) {
        direction = "right"
        timeId = that.recordFor(index, currentTime, direction)
      } else {
        direction = "left"
        timeId = that.recordFor(index, currentTime, direction)
      }
    })
    aduioContext.onEnded(function (e) {
      console.log("监听到语音自然播放停止")
      clearInterval(timeId); //停止帧动画循环  
      that.setData({
        playId: index,
        reImaUrl: reImaUrl + direction + "3.png"
      })
    })
    aduioContext.onStop(function (e) {
      console.log("监听到语音播放暂停")
      clearInterval(timeId); //停止帧动画循环  
      that.setData({
        playId: index,
        reImaUrl: reImaUrl + direction + "3.png"
      })
    })
  },
  //录音播放动画循环
  recordFor: function (index, currentTime, direction) {
    let that = this
    var reImaUrl = "../../static/images/chat/"
    let j = 0,
      count = 0;
    let time = +currentTime * 2
    var timeId = setInterval(function () {
      if (time > count) {
        if (j > 2) {
          j = 0
        }
        j = j + 1;
        count++;
        that.setData({
          playId: index,
          reImaUrl: reImaUrl + direction + j + ".png"
        })
      }
    }, 500)
    return timeId
  },



  //删除单条消息
  delMsg: function (e) {
    var that = this;
    var magIdx = parseInt(e.currentTarget.dataset.index);
    var list = that.data.wxchatLists;
    wx.showModal({
      title: '提示',
      content: '确定撤回此消息吗？',
      success: function (res) {
        if (res.confirm) {
          console.log(e);
          list.splice(magIdx, 1);
          that.setData({
            wxchatLists: list,
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //点击图片 预览大图
  seeBigImg: function (e) {
    var that = this;
    var idx = parseInt(e.currentTarget.dataset.index);
    var src = that.data.wxchatLists[idx].content;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src] // 需要预览的图片http链接列表
    })
  },

});